<template>
  <div class="app-container">
    <div id="app" style="width: 100%;display:inline-block">
      <el-form ref="searchForm" :model="searchForm" label-width="100px">
        <el-col :span="3">
          <el-form-item label="项目名称" label-width="70px">
            <el-input v-model="searchForm.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="承建公司" prop="branch_id" label-width="70px">
            <el-select v-model="searchForm.branch_id">
              <el-option v-for="(val, key) in branch" :key="key" :label="val.name" :value="val.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="选择时间" prop="flow_status" label-width="70px">
            <el-date-picker
              v-model="searchForm.time"
              type="daterange"
              value-format = "timestamp"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions2">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <!--<el-form-item label="搜索" label-width="40px">-->
          <el-button @click="onSubmitSearchForm()" icon="el-icon-search" circle style="float: right;margin-right: 50%"></el-button>
          <!--</el-form-item>-->
        </el-col>
      </el-form>
    </div>
    <!--顶部操作工具栏-->
    <!--<div style="margin: 10px 0">-->
      <!--<el-button @click = "onClickCreateBtn"><i class="el-icon-circle-plus-outline"></i> 新增</el-button>-->
    <!--</div>-->
    <!--编辑表单-->
    <el-dialog :title="this.activeId===0?'新增项目':'编辑项目'" :visible.sync="visible.ruleForm" @close="closeDialog()">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px">
        <el-form-item label="收款日期" prop="receive_date">
          <el-date-picker
            v-model="ruleForm.receive_date"
            type="date"
            value-format = "timestamp"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发票编号" prop="invoice_no">
          <el-input v-model="ruleForm.invoice_no"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="comment">
          <el-input v-model="ruleForm.comment"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="visible.ruleForm = false">关闭</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!--分页器-->
    <div style="padding:0 10px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        :current-page="searchForm.currentPage"
        :page-sizes="[10,30,50,100]"
        :page-size="searchForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="searchForm.totalCount">
      </el-pagination>
    </div>
    <!--列表-->
    <table class="_table" border="0" cellpadding="0" cellspacing="0" style="width: 100%" v-loading="loading.list">
      <thead>
      <tr>
        <th>id</th>
        <th>发票编号</th>
        <th>开票金额</th>
        <th>项目名称</th>
        <th>承建公司</th>
        <th>收款日期</th>
        <th>备注</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="(item, key) in list" :key="key">
        <td>{{item.id}}</td>
        <td>{{item.invoice_no}}</td>
        <td>{{item.money}}</td>
        <td>{{item.project_name.name}}</td>
        <td>{{item.project_name.branch_id | parseBranch}}</td>
        <td>{{item.receive_date | parseTime}}</td>
        <td>{{item.comment}}</td>
        <td>
          <el-button @click="onClickEditBtn(item.id)"><i class="el-icon-edit"></i>修改</el-button>
        </td>
      </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
  import { createReceival, getReceivals, getReceival, updateReceival } from '../../api/receival'
  import { replyRes } from '../../utils/res'
  import { parseTime } from '../../utils'
  import Store from '../../store'
  import { getBranches } from '../../api/branch'

  const defaultRuleForm = {
    comment: '',
    invoice_no: '',
    receive_date: null
  }
  export default {
    data() {
      return {
        /**
         * 创建表单相关变量
         */
        activeId: 0,
        visible: {
          ruleForm: false
        },
        branch: [
          { id: null, name: '全部' }
        ], // 承建单位
        rules: {
          receive_date: [
            { required: true, message: '请输入', trigger: 'blur' }
          ],
          invoice_no: [
            { required: true, message: '请输入', trigger: 'blur' }
          ]
        },
        searchForm: {
          name: '',
          time: [],
          page: 1,
          start_at: null,
          end_at: null,
          pageSize: 10,
          totalCount: 0
        },
        ruleForm: Object.assign({}, defaultRuleForm),
        /**
         * 项目列表相关变量
         */
        loading: {
          list: true
        },
        list: [],
        pickerOptions2: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        }
      }
    },
    computed: {
      branches() {
        return this.$store.state.user.branches
      }
    },
    filters: {
      parseTime: function(value) {
        if (!value) return ''
        value = value.toString()
        return parseTime(value, '{y}年{m}月{d}日')
      },
      parseBranch: function(value) {
        const list = Store.state.user.branches
        for (const index in list) {
          if (parseInt(list[index].id) === value) {
            return list[index].name
          }
        }
        return value
      }
    },
    mounted() {
      this.fetchList()
      this.fetchBranches()
    },
    methods: {
      /**
       * 项目列表相关命令
       */
      fetchList() {
        this.loading.list = true
        getReceivals(this.searchForm).then(res => {
          // console.log('res', res)
          this.list = res.data._items
          this.searchForm.totalCount = res.data._meta.totalCount
          this.loading.list = false
        })
      },
      // 获取承建公司列表
      fetchBranches() {
        getBranches().then(res => {
          for (const x in res.data) {
            this.branch.push(res.data[x])
          }
        })
      },
      fetchOne() {
        getReceival(this.activeId).then(res => {
          res.data.receive_date *= 1000
          this.ruleForm = Object.assign({}, res.data)
        })
      },
      // 一页多少行
      handleSizeChange(pageSize) {
        this.searchForm.pageSize = pageSize
        this.fetchList()
      },
      // 翻页
      handlePageChange(currentPage) {
        this.searchForm.page = currentPage
        this.fetchList()
      },
      /**
       * 创建编辑相关命令
       * */
      onClickCreateBtn() {
        this.activeId = 0
        this.visible.ruleForm = true
      },
      onClickEditBtn(id) {
        this.activeId = id
        this.fetchOne()
        this.visible.ruleForm = true
      },
      onClickDeleteBtn(id) {},
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.ruleForm.receive_date /= 1000
            if (this.activeId === 0) {
              // 调用新增接口并响应
              createReceival(this.ruleForm).then(res => {
                if (replyRes(res)) {
                  this.visible.ruleForm = false
                }
              })
            } else {
              // 调用更新接口并响应
              updateReceival(this.ruleForm).then(res => {
                if (replyRes(res)) {
                  this.visible.ruleForm = false
                }
              })
            }
          } else {
            console.log('ruleForm validate fail')
            return false
          }
        })
      },
      closeDialog() {
        this.ruleForm = Object.assign({}, defaultRuleForm)
        this.fetchList()
      },
      // 搜索
      onSubmitSearchForm() {
        if (this.searchForm.time !== null && this.searchForm.time.length > 0) {
          this.searchForm.start_at = this.searchForm.time[0]
          this.searchForm.end_at = this.searchForm.time[1]
        } else {
          this.searchForm.start_at = null
          this.searchForm.end_at = null
        }
        this.fetchList()
      }
    }
  }
</script>
